package com.example.demo.controller;

import com.example.demo.entity.Admin;
import com.example.demo.service.AdminService;
import com.mysql.cj.util.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
/**
 * @author shenrui
 * @date 2021/9/19
 * @description 设置Admin的行为，包括登录，对用户的增删改查
 */
@Controller
public class AdminController {

    @Resource
    private AdminService adminService;

    /**
     *return String
     * @description 对管理员的登录行为进行判断
     */
    @PostMapping("/admin_login")
    public String adminLogin(Admin admin, HttpServletRequest request, Model model) {
        HttpSession session = request.getSession();
        //防止用户卡bug进入登陆页面
        if (session.getAttribute("adminLogin") != null) {
            return "redirect:admin_main";
        }
        //用户不能同时登录管理员
        if (session.getAttribute("userLogin") != null) {
            return "redirect:user_main";
        }
        if (StringUtils.isNullOrEmpty(admin.getAdAccount()) || StringUtils.isNullOrEmpty(admin.getAdPassword())) {
            model.addAttribute("adminMsg", "请输入用户名或密码");
            return "admin/admin_login";

        }
        Admin myAdmin = adminService.verifyAdminLogin(admin);
        if (myAdmin != null) {
            session.setAttribute("adminLogin", myAdmin);
            return "redirect:admin_main";
        } else {
            model.addAttribute("adminMsg", "用户名或密码错误");
            return "admin/admin_login";
        }

    }

    /**
     *return String
     * @description 管理员退出登录
     */
    @RequestMapping("/admin_logout")
    public String user_logout(HttpSession session) {
        session.invalidate();
        return "redirect:admin_login";
    }


}
